/*
 * @lc app=leetcode id=150 lang=cpp
 *
 * [150] Evaluate Reverse Polish Notation
 */
class Solution {
    unordered_map<std::string, std::function<long(long, long)>> op = {
        {"+", [](long a, long b) { return a+b;}},
        {"-", [](long a, long b) { return a-b;}},
        {"*", [](long a, long b) { return a*b;}},
        {"/", [](long a, long b) { return a/b;}},
    };
public:
    int evalRPN(vector<string>& tokens) {
        deque<long> stack;
        int ret = INT_MAX;
        int result = 0;

        int idx = 0;
        int len = tokens.size();
        while (idx < len) {
            auto& token = tokens[idx++];
            if (op.find(token) != op.end()) {
                if (stack.size() < 2) {     // not valid
                    return ret;
                }

                long b = stack.back();
                stack.pop_back();
                long a = stack.back();
                stack.pop_back();

                if (token.compare("/") == 0) {
                    if (b == 0) {           // not divied by zero
                        return ret;
                    }
                }

                result = op[token](a,b);
                stack.push_back(result);
            } else {
                stack.push_back(stoi(token));
            }
        }

        if (stack.size() != 1) {
            return ret;
        }
        
        return stack.back();
    }
};

